import time

import uvicorn
from fastapi import FastAPI, Request
from tortoise.contrib.fastapi import register_tortoise

from FastAPI.orm_demo.orm_setting import TORTOISE_ORM
from FastAPI.orm_demo.student.student import student

app = FastAPI()


# 中间件示例：记录请求时间
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    import time
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


# 新的中间件：记录请求路径
@app.middleware("http")
async def log_request_path(request: Request, call_next):
    print(f"Request path: {request.url.path}")
    response = await call_next(request)
    return response


@app.get("/user")
def get_user():
    time.sleep(3)
    print("get_user函数执行")
    return {
        "user": "current user"
    }


@app.get("/item/{item_id}")
def get_item(item_id: int):
    time.sleep(2)
    print("get_item函数执行")
    return {
        "item_id": item_id
    }


app.include_router(student, prefix="/student", tags=["3.orm操作", ])

# 该方法会在fastapi启动时触发，内部通过传递进去的app对象，监听服务启动和终止事件
# 当检测到启动事件时，会初始化Tortoise对象，如果generate_schemas为True则还会进行数据库迁移
# 当检测到终止事件时，会关闭连接
register_tortoise(
    app,
    config=TORTOISE_ORM,
    # generate_schemas=True,  # 如果数据库为空，则自动生成对应表单，生产环境不要开
    # add_exception_handlers=True,  # 生产环境不要开，会泄露调试信息
)
if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8080, reload=True)
